<template>
  <div id="login">
    <div class="login-wrap">
      <ul class="menu-tab">
        <li
          v-for="item in menuTab"
          :class="{ current: item.current }"
          :key="item.id"
          @click="toggelMenu(item)"
        >
          {{ item.txt }}
        </li>
      </ul>

      <!-- 表单 start -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        class="login-form"
        size="medium"
      >
        <!-- 邮箱表单 -->
        <el-form-item prop="username" class="item-form">
          <label>邮箱</label>
          <el-input
            type="text"
            v-model="ruleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 密码表单 -->
        <el-form-item prop="password" class="item-form">
          <label>密码</label>
          <el-input
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <!-- 再次输入密码 -->
        <el-form-item
          prop="passwords"
          class="item-form"
          v-if="model === 'register'"
        >
          <label>再次输入密码</label>
          <el-input
            type="password"
            v-model="ruleForm.passwords"
            autocomplete="off"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <!-- 验证码输入 -->
        <el-form-item prop="code" class="item-form">
          <label>验证码</label>
          <el-row :gutter="20">
            <el-col :span="15"
              ><el-input v-model="ruleForm.code" maxlength="6"></el-input
            ></el-col>
            <!-- 获取验证码 -->
            <el-col :span="9">
              <el-button
                type="primary"
                class="block"
                @click="getSms()"
                :disabled="codeButtonStatus.status"
                >{{ codeButtonStatus.text }}</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
        <!-- 提交 -->
        <el-form-item class="item-form">
          <el-button
            type="danger"
            @click="submitForm('loginForm')"
            class="login-btn block"
            :disabled="loginButtonStatus"
            >{{ model === "login" ? "登录" : "注册" }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import sha1 from 'js-sha1';
import {
  stripscript,
  validatePass,
  validateEmail,
  validateVCode,
} from "@/utils/validate";
import { GetSms, Register, Login } from "@/api/login";
import { isRef, onMounted, reactive, ref, toRefs } from "@vue/composition-api";
export default {
  name: "login",
  setup(props, { refs, root }) {
    // 验证邮箱
    let validateUsername = (rule, value, callback) => {
      // let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (validateEmail(value)) {
        callback(new Error("用户格式有误"));
      } else {
        callback(); //返回true
      }
    };

    // 验证密码
    let validatePassword = (rule, value, callback) => {
      // console.log(stripscript(value));
      // 过滤后的密码数据
      ruleForm.password = stripscript(value);
      value = ruleForm.password;
      // let reg = /^(?!\D+$)(?![^a-zA-Z]+$)\S{6,20}$/
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (validatePass(value)) {
        callback(new Error("密码为数字+字母"));
      } else {
        callback();
      }
    };

    // 注册时第二次验证密码
    let validatePasswords = (rule, value, callback) => {
      //如果模块值为login，直接通过，不会再运行后面程序
      if (model.value == "login") {
        return callback();
      }
      console.log(stripscript(value));
      // 过滤后的密码数据
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (ruleForm.password != value) {
        callback(new Error("与第一次密码不符"));
      } else {
        callback();
      }
    };

    // 验证验证码
    let validateCode = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入验证码"));
      } else if (validateVCode(value)) {
        return callback(new Error("验证码格式有误"));
      } else {
        callback();
      }
    };
    // vue3.0创建对象，需要用reactive
    /**
     * 变量声明
     */
    const menuTab = reactive([
      { txt: "登录", current: true, type: "login" },
      { txt: "注册", current: false, type: "register" },
    ]);
    // 模块值 用于切换注册和登录
    const model = ref("login");

    // 倒计时
    const timer = ref(null);

    //登录按钮禁用状态
    const loginButtonStatus = ref(true);
    //验证/注册码按钮状态
    // const codeButtonStatus = ref(false);
    const codeButtonStatus = reactive({
      status: false,
      text: "获取验证码",
    });
    // 表单的数据
    const ruleForm = reactive({
      username: "",
      password: "",
      passwords: "",
      code: "",
    });

    const rules = reactive({
      username: [{ validator: validateUsername, trigger: "blur" }],
      password: [{ validator: validatePassword, trigger: "blur" }],
      passwords: [{ validator: validatePasswords, trigger: "blur" }],
      code: [{ validator: validateCode, trigger: "blur" }],
    });

    /**
     * 生命周期函数
     */
    //挂载完成后
    onMounted(() => {
      // GetSms()
    });

    /**
     * 声明函数
     */
    //切换模块
    const toggelMenu = (data) => {
      menuTab.forEach((elem) => {
        elem.current = false;
      });
      // 每次点击，都将所有改为false，再传入点击的对象，改为true
      data.current = true;
      // 修改模块值
      model.value = data.type;
      // 重置表单
      resetFormData()
      clearCountDown()
    };
    //清除表单数据
    const resetFormData = (() =>{
      refs.loginForm.resetFields();
    })

  

    //提交表单
    const submitForm = (formName) => {
      refs[formName].validate((valid) => {
        console.log(model.value);
        //表单验证通过
        if (valid) {
          if (model.value === "login") {
            login();
          } else {
            register();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };

    /**
     * 登入
     */
    const login = () => {
      let requestData = {
        username: ruleForm.username,
        password: sha1(ruleForm.password),
        code: ruleForm.code,
      };
      root.$store.dispatch('app/login',requestData).then((response) => {
        console.log("登录成功");
        console.log(response.data);
        root.$router.push({
          name:'Console'
        })
      })
      // Login(requestData).then((response) => {
      //   console.log("登录成功");
      //   console.log(response.data);
      //   root.$router.push({
      //     name:'Console'
      //   })
      // });
    };

    /**
     * 注册
     */
    const register = () => {
      let RequestData = {
        username: ruleForm.username,
        password: sha1(ruleForm.password),
        code: ruleForm.code,
        module: "register",
      };
      //注册接口
      Register(RequestData)
        .then((response) => {
          let data = response.data;
          console.log(response);
          root.$message({
            message: data.message,
            type: "success",
          });
          //模拟注册成功
          toggelMenu(menuTab[0]);
          clearCountDown();
        })
        .catch(() => {
          //失败时执行
        });
    };

    const resetForm = (formName) => {
      refs[formName].resetFields();
    };

    //更新按钮状态
    const UpdataButtonStatus = ((params) =>{
      codeButtonStatus.status = params.status
      codeButtonStatus.text = params.text
    })


    // 获取验证码
    const getSms = () => {
      if (ruleForm.username === "") {
        root.$message.error("邮箱内容不能为空");
        return false;
      }

      UpdataButtonStatus({
        status:true,
        text:'发送中'
      })

      if (validateEmail(ruleForm.username)) {
        root.$message.error("邮箱格式有误");
        return false;
      }

      let data = {
        username: ruleForm.username,
        module: model.value,
      };

      setTimeout(() => {
        GetSms(data)
          .then((response) => {
            let data = response.data;
            if (data.resCode == 0) {
              root.$message({
                message: "验证码获取成功",
                type: "success",
              });
            }
            // 启用登录或注册按钮
            loginButtonStatus.value = false;
            // 调定时器，倒计时
            countdown(10);
            codeButtonStatus.text = "发送中";
            console.log(data);
          })
          .catch((error) => {
            console.log(error);
          });
      }, 3000);
    };
    /**
     * 倒计时
     */
    const countdown = (number) => {
      // 判断定时器是否存在，存在则清除定时器
      if (timer.value) {
        clearInterval(timer.value);
      }
      let time = number;
      timer.value = setInterval(() => {
        time--;
        if (time === 0) {
          clearInterval(timer.value);
          UpdataButtonStatus({status:false,text:'再次发送'})
        } else {
          codeButtonStatus.text = `倒计时${time}秒`;
        }
      }, 1000);
    };

    /**
     * 清除倒计时
     */
    const clearCountDown = () => {
      // 还原验证码按钮默认状态
      codeButtonStatus.status = false;
      codeButtonStatus.text = "获取验证码";
      // 清除倒计时
      clearInterval(timer.value);
    };

    return {
      menuTab,
      model,
      loginButtonStatus,
      codeButtonStatus,
      ruleForm,
      rules,
      toggelMenu,
      submitForm,
      resetForm,
      submitForm,
      getSms,
      timer,
      countdown,
      clearCountDown,
    };

    // vue3.0创建基础值需要用 ref，使用时，基础变量用xxx.value取值
    // const model = ref("login");
    // console.log(model.value);
    // isRef判断是否是基础数据类型
    // console.log(isRef(model) ? true : false);

    // const obj = reactive({
    //   x:0,
    //   y:1
    // })
    // console.log(obj);
    // // 将reactive的引用类型转换为基础类型，保证对象结构或拓展运算符不会丢失原有相应式对象的相应
    // const aa = toRefs(obj)
    // console.log(aa.x.value);
  },
};
</script>

<style lang="scss" scoped>
#login {
  height: 100vh;
  background-color: #344a5f;
}
.login-wrap {
  width: 330px;
  margin: 0 auto;
}
.menu-tab {
  text-align: center;
  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
  }
  .current {
    background-color: rgba(0, 0, 0, 0.1);
  }
}

.login-form {
  margin-top: 9px;
  label {
    margin-bottom: 3px;
    display: block;
    font-size: 14px;
    color: #fff;
  }
  .item-form {
    margin-bottom: 13px;
  }
  .block {
    display: block;
    width: 100%;
    height: 33px;
  }
  .login-btn {
    margin-top: 19px;
  }
}
</style>
